<script setup>

import {reactive, ref, watch, watchEffect} from "vue";

//注意：监听的值必须为引用类型
const num = ref(0)

const user = reactive({
  name: '张三',
  age: 19
})


function addNum() {
  num.value++
}

function addAge() {
  user.age++
}

//属性监听
watch(num, (value, oldValue, onCleanup) => {
  console.log("num属性监听===》newValue：" + value + "；oldValue:" + oldValue)
  onCleanup(() => {
    console.log("num属性监听===》onCleanup....")
  })
})
//对象监听
watch(user, (value, oldValue, onCleanup) => {
  console.log(`user对象监听===》newValue： `, value, ` ；oldValue: `, oldValue)
  onCleanup(() => {
    console.log("user对象监听===》onCleanup....")
  })
})
//全局监听
//注意：只有刷新浏览器，对象监听才会触发，属性监听不会触发。
watchEffect(() => {
  console.log(`全局监听===》num： `, num, ` ；对象age属性: `, user.age)
})

</script>

<template>
  <h2>watch-监听</h2>

  <button @click="addNum">num递增</button>
  <button @click="addAge">对象age递增</button>
</template>

<style scoped>
</style>